package main

import (
	"flag"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/zrpc"
	"github.com/zeromicro/zero-contrib/zrpc/registry/nacos" // 引入 Nacos 注册包
	"go-exp/exp-test/nacos-test/server_demo/internal/config"
	"go-exp/exp-test/nacos-test/server_demo/internal/server"
	"go-exp/exp-test/nacos-test/server_demo/internal/svc"
	"go-exp/exp-test/nacos-test/server_demo/server_demo"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

var configFile = flag.String("f", "exp-test/nacos-test/server_demo/etc/serverdemo.yaml", "the config file")

func main() {
	flag.Parse()
	var c config.Config
	conf.MustLoad(*configFile, &c) // 加载配置
	ctx := svc.NewServiceContext(c)

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { // c.RpcServerConf 就是 go-zero 默认的 Server 配置
		server_demo.RegisterServerDemoServer(grpcServer, server.NewServerDemoServer(ctx)) // 注册你的 gRPC 服务实现

		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer s.Stop()

	// 注册服务到 Nacos
	// 确保你的 config.Config 结构体中包含了 Nacos 配置 (例如 c.Nacos)
	// 这里的 c.Nacos 应该是 `nacos.Conf` 类型
	if err := nacos.RegisterService(&nacos.Options{
		ListenOn:    c.ListenOn,
		ServiceName: c.Name,
		ServerConfig: []constant.ServerConfig{
			*constant.NewServerConfig(
				c.NacosConf.IpAddr,
				c.NacosConf.Port,
			),
		},
	}); err != nil { // c.Nacos 对应上面 YAML 中的 Nacos 块
		panic(err)
	}
	// 如果你的 Nacos 配置不在 c.Nacos 下，而是如 Registry.Nacos，你需要调整这里的 c.Nacos

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
